package com.example.springworkfront.Service;

import com.example.springworkfront.pojo.Units;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

@Service
public class InitServices implements InitializingBean {
    public static List<Units> unitsList = new ArrayList<>();
    public static List<Units> keyList = new ArrayList<>();
    public static final String URL = "https://gitee.com/spverk/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv";

    @Scheduled(cron = "0 0 2 * * *")
    public void fetchCoronaVirusData() throws IOException {
        RequestEntity<Void> requestEntity =
                RequestEntity.get(URI.create(URL))
                        .headers(httpHeaders -> httpHeaders.add("User-Agent", "huang"))
                        .build();
        ResponseEntity<Resource> exchange = new RestTemplate().exchange(requestEntity, Resource.class);
        Resource body = exchange.getBody();

        System.out.println(body);
        final Reader reader = new InputStreamReader(body.getInputStream(), "UTF-8");
        final CSVParser parser = new CSVParser(reader, CSVFormat.EXCEL.withHeader());
        unitsList.clear();
        try {
            for (final CSVRecord record : parser) {
                Units units = new Units(
                        record.get("Province/State"),
                        record.get("Country/Region"),
                        Integer.valueOf(record.get(record.size() - 1)),
                        Integer.valueOf(record.get(record.size() - 1)) - Integer.valueOf(record.get(record.size() - 2))
                );
                unitsList.add(units);
            }
            for (Units units : InitServices.unitsList) {
                // System.out.println(units.getCountry());
                if ("China".equals(units.getCountry())) {
                    keyList.add(units);
                }
            }
            //System.out.println(unitsList);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            parser.close();
            reader.close();
        }

    }

    public void afterPropertiesSet() throws IOException {
        fetchCoronaVirusData();
    }
}
